import React from 'react';
import { Outlet, Link, useNavigate } from 'react-router-dom';
import { Layout, Menu, Button, Avatar, Dropdown, Input, Space } from 'antd';
import { UserOutlined, SearchOutlined, LogoutOutlined, SettingOutlined } from '@ant-design/icons';
import '../styles/App.css';

const { Header, Content, Footer } = Layout;

const MainLayout: React.FC = () => {
  const navigate = useNavigate();
  
  // 模拟用户信息，实际应用中应从状态管理或API获取
  const user = {
    nickname: '用户',
    avatar: '',
  };

  const handleSearch = (value: string) => {
    navigate(`/search?keyword=${encodeURIComponent(value)}`);
  };

  const handleLogout = () => {
    // 实际应用中应调用登出API
    localStorage.removeItem('token');
    navigate('/login');
  };

  const userMenu = [
    {
      key: 'profile',
      icon: <UserOutlined />,
      label: '个人资料',
      onClick: () => navigate('/profile'),
    },
    {
      key: 'settings',
      icon: <SettingOutlined />,
      label: '设置',
      onClick: () => navigate('/settings'),
    },
    {
      key: 'logout',
      icon: <LogoutOutlined />,
      label: '退出登录',
      onClick: handleLogout,
    },
  ];

  return (
    <Layout className="app-layout">
      <Header className="app-header">
        <div className="app-logo">
          <Link to="/">
            <img src="/logo.svg" alt="myKng" height="32" />
          </Link>
        </div>
        <Menu
          mode="horizontal"
          defaultSelectedKeys={['home']}
          style={{ flex: 1, minWidth: 0 }}
          items={[
            { key: 'home', label: <Link to="/">首页</Link> },
            { key: 'knowledge', label: <Link to="/knowledge">知识库</Link> },
          ]}
        />
        <Space size="large">
          <Input.Search
            placeholder="搜索知识..."
            onSearch={handleSearch}
            style={{ width: 300 }}
          />
          <Dropdown menu={{ items: userMenu }} placement="bottomRight">
            <Button type="text" icon={user.avatar ? null : <UserOutlined />}>
              {user.avatar ? (
                <Avatar src={user.avatar} size="small" />
              ) : null}
              <span style={{ marginLeft: 8 }}>{user.nickname}</span>
            </Button>
          </Dropdown>
        </Space>
      </Header>
      <Content className="app-content">
        <Outlet />
      </Content>
      <Footer className="app-footer">
        myKng - 个人知识管理系统 ©{new Date().getFullYear()} 版权所有
      </Footer>
    </Layout>
  );
};

export default MainLayout;